"""This module provides video creation functionality with local configuration"""

import json
import os
import platform

from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
from moviepy.video.VideoClip import ImageClip


class VideoCreator:
    """
    A class to create videos from images and audio.

    Parameters:
    - config_path (str): Path to the configuration JSON file containing input and output paths
    """

    def __init__(self, config_path: str):
        self.config_path = config_path
        self.config = self._load_config()

        # Get paths from config
        self.image_path = self.config.get("image_path")
        self.audio_path = self.config.get("audio_path")
        self.output_path = self.config.get("output_path")

        # Validate config
        if not all([self.image_path, self.audio_path, self.output_path]):
            raise ValueError(
                "Config must contain image_path, audio_path, and output_path"
            )

        # Validate input files exist
        if not os.path.exists(self.image_path):
            raise FileNotFoundError(f"Image file not found: {self.image_path}")
        if not os.path.exists(self.audio_path):
            raise FileNotFoundError(f"Audio file not found: {self.audio_path}")

    def _load_config(self) -> dict:
        """Load configuration from JSON file"""
        try:
            with open(self.config_path, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception as e:
            raise RuntimeError(f"Error loading config file: {str(e)}") from e

    def create_video(self) -> str:
        """
        Create a video from the specified image and audio files.

        Returns:
        - str: Path to the created video file
        """
        try:
            # 创建音频 clip
            audio = AudioFileClip(self.audio_path)
            # 创建图片 clip
            image = ImageClip(self.image_path, duration=audio.duration)
            # 合成视频（把图片 clip 放到 CompositeVideoClip 里）
            video = CompositeVideoClip([image])

            # 设置音频
            video.audio = audio
            # 导出视频
            # https://zulko.github.io/moviepy/reference/reference/moviepy.video.VideoClip.VideoClip.html#moviepy.video.VideoClip.VideoClip.write_videofile
            video.write_videofile(
                self.output_path, fps=24, codec="libx264", audio_codec="aac", threads=4
            )
            # 关闭资源
            audio.close()
            image.close()
            video.close()
            return self.output_path
        except Exception as e:
            raise RuntimeError(f"Error creating video: {str(e)}") from e


def main():

    sys = platform.system()
    if sys == "Windows":
        config_path = r"D:\python\p1_good_night\mp3tomp4\util\mp3tomp4.json"
    elif sys == "Darwin":
        config_path = (
            "/Users/wangchuanyi/money/years/p1_good_night/mp3tomp4/util/mp3tomp4.json"
        )
    else:
        config_path = "/root/bin/mp3tomp4.json"

    try:
        # 初始化 VideoCreator 并创建视频
        creator = VideoCreator(config_path)
        result_path = creator.create_video()
        print(f"视频创建成功，保存在: {result_path}")
    except Exception as e:
        print(f"创建视频时出错: {str(e)}")


if __name__ == "__main__":
    main()
